package com.fxu.tpl.api;

import com.fxu.framework.biz.ano.Logger;
import com.fxu.framework.core.service.impl.ApiServiceImpl;
import com.fxu.framework.core.sql.SUtils;
import com.fxu.tpl.entity.Test;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/***
 * <p>fxu</p>
 * 测试API接口
 * @author fangxu
 * @version 2021-03-13
 ***/
@Slf4j
@RestController
@RequestMapping("/testApi")
@Api(tags = "测试Api")
@RequiredArgsConstructor
public class TestAsyncService {
	private final ApiServiceImpl apiService;

//	@Async
//	@EventListener
//	public boolean asyncUpdate(Long id, int status) {
//		return apiService.updateBy(SUtils.update(Test.class).id(id).set(Test::getStatus, status + 1).eq(Test::getStatus, status));
//	}

	@Logger
	public void printTest(Long id) {
		Test test = apiService.findLast(SUtils.query(Test.class).id(id));
		System.out.println(test);
	}

	@Transactional
	public boolean innerTransactional(Long id, Integer status, boolean exception) {
		boolean ret = apiService.updateBy(SUtils.update(Test.class).id(id).set(Test::getStatus, status));
		if (exception) {
			throw new RuntimeException("测试事务");
		}
		return ret;
	}

	@Async
	@EventListener
	// 异步清算[需要做Job补偿]
	public void handleAsync(TestAsyncEvent event) {
		log.info("handleAsync event={}", event);
		apiService.updateBy(SUtils.update(Test.class).id(event.getId()).set(Test::getStatus, event.getStatus() + 1).eq(Test::getStatus, event.getStatus()));

	}
}